/*
 * @lc app=leetcode.cn id=508 lang=cpp
 *
 * [508] 出现次数最多的子树元素和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> findFrequentTreeSum(TreeNode* root) {
        //所有节点都有一个值
        dfs(root);
        return ans;
    }
private:
    unordered_map<int, int> hash;
    vector<int> ans;
    int maxc = 0;
    int dfs(TreeNode* t){
        if(t == nullptr) return 0;
        int sum = t->val + dfs(t->left) + dfs(t->right);
        hash[sum]++;
        if(hash[sum] > maxc){
            maxc = hash[sum];
            vector<int>().swap(ans);    //实现vector的空间释放
            ans.push_back(sum);
        }else if (hash[sum] == maxc){
            ans.push_back(sum);
        }
        return sum;
    }
};
// @lc code=end

